package cn.westv.scps.web.controller.agent;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunpian.sdk.constant.Config;

import cn.westv.scps.connTools.ProxyConnExec;
import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.domain.PublishAgentEntity;
import cn.westv.scps.service.agent.IAgentService;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.utils.Page;
import cn.westv.scps.web.controller.agent.vo.AgentFormVO;
import cn.westv.scps.web.controller.areaserver.AreaServerController;
import cn.westv.scps.web.controller.base.AbstractController;

/**
 * 运营商管理
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/sys/agent")
public class AgentController extends AbstractController<AgentController> {

	@Autowired
	IAgentService agentService;

	@Autowired
	IAreaServerService areaServer;

	@RequestMapping("/index.cgi")
	public String toIndex_cgi() {
		return "forward:/WEB-INF/page/sys/agent/agentIndex.jsp";
	}

	@RequestMapping("/edit.cgi")
	public String toEdit_cgi() {
		return "forward:/WEB-INF/page/sys/agent/agentEdit.jsp";
	}

	/**
	 * 分页条件查找代理商信息
	 * 
	 * @param agentFormVO
	 * @param page
	 * @return 返回Page对象
	 */
	@ResponseBody
	@RequestMapping("/pagelist")
	public Map<String, Object> agentFindPage(AgentFormVO agentFormVO, Page<PublishAgentEntity> page) {
		try {
			String hql = "from PublishAgentEntity where 1 = 1 ";
			List<Object> paramList = new ArrayList<Object>();
			PublishAgentEntity entity = agentFormVO.getPublishAgentEntity();
			if (entity != null) {
				String id = entity.getAgentId();
				if (StringUtils.isNotBlank(id)) {
					hql += " and " + " agentId = ?";
					paramList.add(id);
				}
				String name = entity.getAgentName();
				if (StringUtils.isNotBlank(name)) {
					hql += " and " + "agentName like ?";
					paramList.add("%" + name + "%");
				}
				String identity = entity.getIdentity();
				if (StringUtils.isNotBlank(identity)) {
					hql += " and " + " identity like ?";
					paramList.add("%" + identity + "%");
				}
				String account = entity.getAccount();
				if (StringUtils.isNotBlank(account)) {
					hql += " and " + " account like ?";
					paramList.add("%" + account + "%");
				}
				String password = entity.getPassword();
				if (StringUtils.isNotBlank(password)) {
					hql += " and " + " password = ?";
					paramList.add(password);
				}
				String address = entity.getAddress();
				if (StringUtils.isNotBlank(address)) {
					hql += " and " + " address like ?";
					paramList.add("%" + address + "%");
				}
				String phone = entity.getPhoneNumber();
				if (StringUtils.isNotBlank(phone)) {
					hql += " and" + " phoneNumber like ?";
					paramList.add("%" + phone + "%");
				}
				AreaSeverEntity server = entity.getAreaSever();
				if (server != null) {
					String serverName = server.getServerName();
					if (StringUtils.isNotBlank(serverName)) {
						hql += " and " + "areaSever.serverName like ?";
						paramList.add("%" + serverName + "%");
					}
				}

			}
			Page<PublishAgentEntity> findPage = agentService.findPage(hql, page, PublishAgentEntity.class,
					paramList.toArray());

			List<PublishAgentEntity> results = findPage.getResults();
			if (results != null && results.size() > 0) {
				for (PublishAgentEntity publishAgentEntity : results) {
					// 解决映射死循环问题,并且只将特定字段内容呈现
					AreaSeverEntity areaSeverEntity = publishAgentEntity.getAreaSever();
					AreaSeverEntity temp = new AreaSeverEntity();
					if (areaSeverEntity != null) {
						// 服务器信息呈现serverId和serverName
						temp.setServerName(areaSeverEntity.getServerName());
						temp.setServerId(areaSeverEntity.getServerId());
					}
					publishAgentEntity.setAreaSever(temp);

					// publishAgentEntity.setAccount(null);
					publishAgentEntity.setPassword(null);

				}
			}
			findPage.setLinks(null);
			// Map<String, Object> params = new HashMap<String, Object>();
			// params.put("data", data);
			// findPage.setParams(params);JSON.parseObject(JSON.toJSONString(findPage))
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);

		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 保存代理商信息
	 * 
	 * @param agentFormVO
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String, Object> saveAgent(AgentFormVO agentFormVO) {
		try {
			if (agentFormVO == null || agentFormVO.getPublishAgentEntity() == null
					|| agentFormVO.getPublishAgentEntity().getAreaSever() == null
					|| StringUtils.isEmpty(agentFormVO.getPublishAgentEntity().getAreaSever().getServerId())) {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
			String returnCode = ""; // 返回的文案代码
			PublishAgentEntity publishAgentEntityDB = null;// 最终写入数据库中的信息
			AreaSeverEntity severEntity = null;
			PublishAgentEntity publishAgentEntity = agentFormVO.getPublishAgentEntity();// 修改或增加的信息
			// -----获取需要映射的server对象----- 保存到数据库之前，需要关联此server对象
			String serverId = publishAgentEntity.getAreaSever().getServerId();
			severEntity = areaServer.get(AreaSeverEntity.class, serverId);
			if (severEntity == null) {
				return ajaxReturnMap(OP_STATUS_FAILD, "请选择正确的服务器", null);
			}
			// -----获取需要映射的server对象-----
			// -------------处理保存逻辑-------------
			if (StringUtils.isEmpty(publishAgentEntity.getAgentId())) { // id为空为新增的逻辑
				String account = publishAgentEntity.getAccount();
				List<PublishAgentEntity> find = agentService.find("from PublishAgentEntity where account = ?",
						PublishAgentEntity.class, new Object[] { account });
				if (find != null && find.size() > 0) {
					return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，代理商账号已存在！", account);
				}
				publishAgentEntityDB = publishAgentEntity;
				publishAgentEntity.setAreaSever(severEntity);
				publishAgentEntityDB.setAgentId(null);
				returnCode = ConfigCodeConstant.ADD_SUCCEED;
			} else {// id不为空为修改的逻辑
				Class<PublishAgentEntity> clazz = PublishAgentEntity.class;
				// 代理服务商不允许修改映射的服务器，所以这里不会重新关联代理商对象和服务器对象
				publishAgentEntityDB = agentService.get(clazz, publishAgentEntity.getAgentId());
				Field[] fields = clazz.getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);
					Object fieldObject = field.get(publishAgentEntity);
					if (fieldObject instanceof String && StringUtils.isNotBlank((String) fieldObject)) { // 排除空
						field.set(publishAgentEntityDB, fieldObject);// 对所有字符串类型的数据进行“复制”
					}
				}
				returnCode = ConfigCodeConstant.UPDATE_SUCCEED;
			}
			// -------------处理保存逻辑-------------
			// 此处需要想base服务器发送添加/修改代理商账号的请求，如果添加成功，则保存数据，否则不保存
			JSONObject jsonObject = ProxyConnExec.savePublishAgentUser(publishAgentEntityDB, severEntity);
			System.out.println(jsonObject);
			if (jsonObject != null && jsonObject.getString("opStatus").equals(OP_STATUS_SUCCESS)) {
				publishAgentEntityDB.setIdentity(jsonObject.getString("data"));
				agentService.saveOrUpdate(publishAgentEntityDB);// 保存数据
			} else {
				return ajaxReturnMap(jsonObject.getString("opStatus"), jsonObject.getString("msgDesc"),
						jsonObject.get("data"));
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, returnMsg(returnCode), null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 条件查询所有
	 * 
	 * @param agentFormVO
	 * @return 返回 代理商的信息和服务器的某些信息（serverId和ServerName）
	 *         若代理商没有相关联的服务器信息，则AreaSever为空 示例：
	 *         {"areaSever":{"serverName":"泸州","serverId":"1"},"agentName":"代理1","address":"address","phoneNumber":"13130543054","identity":"111111","agentId":"1"}
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> listAgent(AgentFormVO agentFormVO) {
		List<PublishAgentEntity> list = null;// 保存查询结果集
		List<Object> paramlist = new ArrayList<Object>();
		String hql = "from PublishAgentEntity where 1 = 1 ";
		try {
			PublishAgentEntity publishAgentEntity = agentFormVO.getPublishAgentEntity();
			// 拼接查询条件
			if (publishAgentEntity != null) {
				String agentId = publishAgentEntity.getAgentId();
				if (StringUtils.isNotBlank(agentId)) {
					hql += " and" + " agentId = ?";
					paramlist.add(agentId);
				}
				String agentName = publishAgentEntity.getAgentName();
				if (StringUtils.isNotBlank(agentName)) {
					hql += " and" + " agentName like ?";
					paramlist.add("%" + agentName + "%");
				}
				String identity = publishAgentEntity.getIdentity();
				if (StringUtils.isNotBlank(identity)) {
					hql += " and" + " identity like ?";
					paramlist.add("%" + identity + "%");
				}
				String account = publishAgentEntity.getAccount();
				if (StringUtils.isNotBlank(account)) {
					hql += " and" + " account like ?";
					paramlist.add("%" + account + "%");
				}
				String password = publishAgentEntity.getPassword();
				if (StringUtils.isNotBlank(password)) {
					hql += " and" + " password = ?";
					paramlist.add(password);
				}
				String address = publishAgentEntity.getAddress();
				if (StringUtils.isNotBlank(address)) {
					hql += " and" + " address like ?";
					paramlist.add("%" + address + "%");
				}
				String phoneNumber = publishAgentEntity.getPhoneNumber();
				if (StringUtils.isNotBlank(phoneNumber)) {
					hql += " and" + " phoneNumber like ?";
					paramlist.add("%" + phoneNumber + "%");
				}
				// 服务器名称
				AreaSeverEntity server = publishAgentEntity.getAreaSever();
				if (server != null) {
					String serverName = server.getServerName();
					if (StringUtils.isNotBlank(serverName)) {
						hql += " and " + "areaSever.serverName like ?";
						paramlist.add("%" + serverName + "%");
					}
				}
			}

			list = agentService.find(hql, PublishAgentEntity.class, paramlist.toArray());
			if (list != null && list.size() > 0) {
				for (PublishAgentEntity agent : list) {
					// 解决映射死循环问题，并只呈现特定字段
					AreaSeverEntity areaSeverEntity = agent.getAreaSever();
					AreaSeverEntity temp = null;// 中间对象，用于存放要呈现服务器信息的字段信息，最终返回的areaServer对象
					if (areaSeverEntity != null) {
						temp = new AreaSeverEntity();
						temp.setServerName(areaSeverEntity.getServerName());
						temp.setServerId(areaSeverEntity.getServerId());
					}
					// 服务器信息呈现serverId和serverName
					agent.setAreaSever(temp);

					agent.setAccount(null);
					agent.setPassword(null);
				}
			}

			return ajaxReturnMap(OP_STATUS_SUCCESS, "", JSON.parseArray(JSON.toJSONString(list)));

		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 删除代理商
	 * 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public Map<String, Object> delAgent(String ids) {

		try {
			String[] idArr = null;
			if (StringUtils.isNotBlank(ids)) {
				idArr = ids.split(","); // 根据id批量删除，id之间使用","分隔
			}
			String msg = "";
			for (String id : idArr) {
				PublishAgentEntity entity = agentService.get(PublishAgentEntity.class, id);
				JSONObject jsonObject = ProxyConnExec.delPublishAgentUser(entity.getIdentity(), entity.getAreaSever());
				if (jsonObject != null && jsonObject.getString("opStatus").equals(OP_STATUS_SUCCESS)) {
					agentService.deleteById(PublishAgentEntity.class, id);
				}
			}
			msg = ConfigCodeConstant.DEL_SUCCEED;
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据agentId查找代理商
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/detail")
	public Map<String, Object> detailAgentById(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL + "（id为空）", null);
		}
		try {
			PublishAgentEntity publishAgentEntity = agentService.get(PublishAgentEntity.class, id);

			AreaSeverEntity areaSeverEntity = publishAgentEntity.getAreaSever();
			AreaSeverEntity temp = new AreaSeverEntity();
			temp.setServerName(areaSeverEntity.getServerName());
			temp.setServerId(areaSeverEntity.getServerId());
			// 服务器信息呈现serverId和serverName
			publishAgentEntity.setAreaSever(temp);

			return ajaxReturnMap(OP_STATUS_SUCCESS, "", publishAgentEntity);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}

	}

	/**
	 * 根据发卡用户，获取对应的服务器对象
	 * 
	 * @param account
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/mapper")
	public Map<String, Object> mapper(String account) {
		try {
			if (StringUtils.isEmpty(account)) {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.LOGIN_FAILURE), null);// 用户名为空，返回错误信息
			}
			JSONObject json = null;
			PublishAgentEntity agentEntity = agentService.findAgentByAccount(account);
			if (agentEntity == null || agentEntity.getAreaSever() == null) {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_OWNER), null);// 用户名不存在
			}
			AreaSeverEntity areaSever = agentEntity.getAreaSever();
			json = new JSONObject();
			// json.put("account", entity.getAccount());
			json.put("serverName", areaSever.getServerName());
			json.put("contextPath", areaSever.getContextPath());
			json.put("areaCode", areaSever.getAreaCode());
			json.put("mqttHostIp", areaSever.getMqttHostIp());
			json.put("socketPort", areaSever.getMqttSocketHostPort());
			json.put("tcpPort", areaSever.getMqttTcpHostPort());
			json.put("serverId", areaSever.getServerId());
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", json);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

}
